<template>
  <el-button
    type="primary"
    :loading="loadData.field"
    @click="submitRepairField()"
    :disabled="props.isDisabled"
    >更新“头像、昵称”字段数据</el-button
  >
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import { getRepairList, getRepairDetail, updateRepair } from '@/apis/repair';
import { createRandomStr } from '@/utils/util';

const dbname = 'user';

// props
const props = defineProps({
  isDisabled: {
    type: Boolean,
    default: false
  }
});

const loadData = reactive({
  field: false
});

/**
 * 更新字段
 */
const submitRepairField = async (page: number = 1) => {
  loadData.field = true;

  // 每次取20条数据
  const maxLimit = 20;
  const resList = await getRepairList<API.user.EntitySchema[]>(dbname, {
    page,
    limit: maxLimit
  });

  if (!resList.data.data || !resList.data.data.length) {
    console.warn('执行结束');
    loadData.field = false;
    return;
  }

  // 循环所有数据
  for (let i = 0; i < resList.data.data.length; i++) {
    const item = resList.data.data[i];

    const res = await getRepairDetail<API.user.EntitySchema>(dbname, item.id!);

    const dataOpt: any = {};

    // 检查会员是否有头像、昵称
    if (res.data.avatar && res.data.nickname) continue;

    console.group('更新table字段');
    console.log(
      `[Limit] - ${maxLimit} -- [Page] - ${page} -- [Current] - ${i + 1}`
    );
    console.log(`[ID] - ${res.data.id}`);
    console.log(`[ownId] - ${res.data.ownId}`);

    console.log(`--------更新字段--------`);

    if (!res.data.avatar) {
      dataOpt['avatar'] = '/static/image/user-avatar/1.png';
      console.log(`[avatar - New] - ${dataOpt.avatar}`);
    }
    if (!res.data.nickname) {
      dataOpt['nickname'] = '微信用户_' + createRandomStr(6, 'complex');
      console.log(`[nickname - New] - ${dataOpt.nickname}`);
    }

    console.groupEnd();

    try {
      await updateRepair(dbname, res.data.id!, dataOpt);
    } catch (error) {
      console.error('submitRepairField', error);
      loadData.field = false;
      return;
    }
  }

  setTimeout(() => {
    submitRepairField(page + 1);
  }, 2 * 1000);
};
</script>

<style lang="scss" scoped></style>
